'''
Author: xiaonancheng
Date: 2023-07-04 14:43:16
https://www.cnblogs.com/xiaonancheng
Copyright (c) 2023 by @xiaonancheng, All Rights Reserved. 
'''
from django.shortcuts import render,redirect
from django.http import JsonResponse

from BoosAPP.models import Boos,Food,F_type
from UserAPP.models import User
# from Staff.models import Staff 




def index(request):#首页
    return render(request,'index.html',{})
def login(request):#登陆页面
    

    if request.method=="GET" and not request.session.get('is_login',None):# 后半句 判断是否登陆
        return render(request,'login.html',)
    elif request.method=="POST" and not request.session.get('is_login',None):
        username=request.POST.get('username')
        password=request.POST.get('password')
        u_c=request.POST.get('u_c')
        if not username:
            # 不填用户名 直接提交 "" None
            return render(request,'login.html',{'msg':'用户不能为空','u_c':u_c})
        if (not u_c) or (u_c not in ['boos','staff','user']):
            # 不填用户名 直接提交 "" None
            return render(request,'login.html',{'msg':'用户类型不能为空或者类型不支持','username':username})
        if u_c =='boos':
            users=Boos.objects.filter(name=username)
        if u_c =='staff':
            users=Boos.objects.filter(name=username)
        if u_c =='user':
            users=User.objects.filter(name=username)
        if not users:
            # 用户名 不存在
            return render(request,'login.html',{'msg':'用户不存在','username':username,'u_c':u_c})
        user=users[0]
        if user.password != password:
            # 密码错误
            return render(request,'login.html',{'msg':'密码错误','username':username,'u_c':u_c})
        # 一切通过 登陆成功 
        request.session['is_login']=True# 是否登陆
        request.session['id']=user.pk
        request.session['username']=user.name
        request.session['u_type']=u_c


        return redirect('/')#到首页
    else:
        return JsonResponse({'msg':'非法请求'})
def logout(request):#登出页面
    if request.session.get('is_login',None):
        request.session['is_login']=False# 是否登陆
        request.session['id']=''
        request.session['username']=''
        request.session['u_type']=''
        return redirect('/')#到首页
    else:
        return redirect('/')#到首页

def register(request):#注册页面
    pass

